function saveListName() {
    /* 返回的是一个validate对象，这个对象有一个form方法，返回的是是否通过验证 */
    var validate = $('#form1').validate({
        rules: {
            name: {required: true, maxlength: 30},
            description: {maxlength: 60},
            apiName: {
                remote: {
                    url: "/listName/vApiName", //后台处理程序
                    type: "post",               //数据发送方式
                    dataType: "json",           //接受数据格式
                    data: {                     //要传递的数据
                        id: $("#entityId").val(),
                        apiName: function () {
                            return $('#form1 input:text[name=apiName]').val();
                        }
                    }
                    // 返回的数据只能是"true" 或 "false"
                    // true:验证通过，false验证失败
                },
                maxlength: 30
            }
        },
        messages: {
            name: {required: "必填字段!", maxlength: "最多可以输入{0}个字符!"},
            description: {maxlength: "最多可以输入{0}个字符!"},
            apiName: {remote: "apiName已存在!", maxlength: "最多可以输入{0}个字符!"}
        },
        highlight: function (element) {
// 				$(element).parent('td').find('label').before('<br>');
        },
        success: function (element) {
        }
    });
    $('#form1').submit();
}

$(function () {
    //返回按钮
    $('#btnBack').on({
        click: function () {
            $('#backForm').submit();
        }
    });
})

$(document).ready(function () {
    var sPage = $("input[name=sPage]").val();
    var sRows = $("input[name=sRows]").val();
    var simpleListTotal = $("#simpleListTotal").val();
    $('ul#rolePagination').page({
        "curPage": parseInt(sPage),
        "pageSize": parseInt(sRows),
        "totalCount": parseInt(simpleListTotal),
        "init": true,
        "callback": function (page) {
            query(page);
        }
    });

    //查询按钮
    $('#btnQuery').on({
        click: function () {
            $('input:hidden[name=sPage]').val(1);
            $('#queryForm').submit();
        }
    });

    //状态选择框
    $("select[name='listValueEnabled']").select2({
        language: "zh-CN",
        placeholder: '请选择',
        minimumResultsForSearch: -1,
        allowClear: true
    });

    //重置按钮
    $('#btnReset').on({
        click: function () {
            $('#queryForm input,select').not('input:hidden[name=page],input:hidden[name=rows],input:hidden[name=id],input:hidden[name=tab]').val('');
            $('input:hidden[name=sPage]').val(1);
            $('input:hidden[name=sRows]').val(10);
            //状态选择框
            $("select[name='listValueEnabled']").select2({
                language: "zh-CN",
                placeholder: '请选择',
                minimumResultsForSearch: -1,
                allowClear: true
            });
        }
    });

    $('#batchSaveSimpleList').on('click', function () {
        $.ajax({
            type: 'post',
            url: '/listEntry/saveBatchValues',
            data: {
                listId: $("#entityId").val(),
                entryValues: $('#simpleListEntryValues').val(),
                listNameApi: $("#entityApiName").val()
            },
            success: function (data) {
                if (!data.success) {
                    $("#simpleListTip").html(data.reason);
                    //alert(data.reason);
                } else {
                    $("#simpleListTip").html("");
                    $('#batchAddSimpleList').modal('hide');
                    $('#tabForm input[name=tab]').val('simpleList');
                    $('#tabForm').submit();
                }
            }
        });
    });

    $('#saveSimpleList').on('click', function () {
        var validate = $('#simpleListForm').validate({
            rules: {
                entryValue: {required: true, maxlength: 60},
                description: {maxlength: 60},
                sortNumber: {digits: true}
            },
            messages: {
                entryValue: {required: "必填字段!", maxlength: "最多可以输入{0}个字符!"},
                description: {maxlength: "最多可以输入{0}个字符!"},
                sortNumber: {digits: '只能输入整数'}
            },
            highlight: function (element) {
//		 				$(element).parent('td').find('label').before('<br>');
            },
            success: function (element) {
            }
        });
        if (validate.form()) {
            var arr = $('#simpleListForm').serializeArray();
            var param = {};
            for (var i = 0; i < arr.length; i++) {
                param[arr[i].name] = arr[i].value;
            }

            $.ajax({
                type: "post",  //提交方式
                dataType: "json", //数据类型
                data: param,
                async: false,
                url: "/listEntry/saveOrUpdate", //请求url
                success: function (data) { //提交成功的回调函数
                    if (!data.success) {
                        //alert(data.reason);
                        $("#simpleEntryTip").html(data.reason);
                    } else {
                        $("#simpleEntryTip").html("");
                        $('#addSimpleList').modal('hide');
                        $('#tabForm input[name=tab]').val('simpleList');
                        $('#tabForm').submit();
                    }
                }
            });
        }
    });

    //编辑按钮
    $("#simpleListTable td a[name='edit']").on({
        click: function() {
            var tr = $(this).parent("td").parent("tr");
            $('#simpleListForm input[name=id]').val(tr.children('td[field=id]').html());
            $('#simpleListForm input[name=listId]').val(tr.children('td[field=listId]').html());
            $('#simpleListForm input[name=entryValue]').val(tr.children('td[field=entryValue]').html());
            $('#simpleListForm input[name=description]').val(tr.children('td[field=description]').html());
            $('#simpleListForm input[name=sortNumber]').val(tr.children('td[field=sortNumber]').html());
            $('#simpleListForm input[name=apiName]').val(tr.children('td[field=apiName]').html());
            $('#simpleListForm select[name=enabled]').val(tr.children('td[field=enabled]').html());
            $('#addSimpleList').modal('show');
        }
    });
});

function query(cp) {
    $('#queryForm input:hidden[name=tab]').val('simpleList');
    /* $('#tabForm input:hidden[name=page]').val(cp);
     $('#tabForm input:hidden[name=rows]').val(10); */
    $('#queryForm input:hidden[name=sPage]').val(cp);
    $('#queryForm input:hidden[name=sRows]').val(10);
    $('#queryForm').submit();
}

function edit(li) {
    $('#simpleListForm input[name=id]').val($(li).children('td[field=id]').html());
    $('#simpleListForm input[name=listId]').val($(li).children('td[field=listId]').html());
    $('#simpleListForm input[name=entryValue]').val($(li).children('td[field=entryValue]').html());
    $('#simpleListForm input[name=description]').val($(li).children('td[field=description]').html());
    $('#simpleListForm input[name=sortNumber]').val($(li).children('td[field=sortNumber]').html());
    $('#simpleListForm input[name=apiName]').val($(li).children('td[field=apiName]').html());
    $('#simpleListForm select[name=enabled]').val($(li).children('td[field=enabled]').html());
    $('#addSimpleList').modal('show');
}

function showAddSimpleList() {
    $('#addSimpleList input[name=id]').val('');
    $('#addSimpleList input[name=parentId]').val('');
    $('#addSimpleList input[name=entryValue]').val('');
    $('#addSimpleList input[name=description]').val('');
    $('#addSimpleList input[name=sortNumber]').val('');
    $('#addSimpleList input[name=apiName]').val('');
    $('#addSimpleList select[name=enabled]').val('1');
    $('#addSimpleList').modal('show');
}

var setting = {
    check: {
        enable: true,
        chkStyle: "radio",
        radioType: "all"
    },
    // 使ztree的对象和后台json对象的字段对应
    data: {
        key: {
            name: "entryValue"
        },
        simpleData: {
            enable: true,
            idKey: 'id',
            PidKey: 'parentId'
        }
    },
    // 异步加载子节点配置
    async: {
        enable: true,
        url: "listEntry/selectTreeData",
        autoParam: ["id=parentId", "enabled=enabled"],
        otherParam: {"listId": $("#entityId").val()},
        dataFilter: filter
    },
    callback: {
        onDblClick: zTreeOnDblClick
    },
    view: {
        // 禁用双击展开
        dblClickExpand: false,
        fontCss: getFont,
        nameIsHTML: true
    }
};

function filter(treeId, parentNode, childNodes) {
    if (!childNodes) return null;
    for (var i = 0, l = childNodes.length; i < l; i++) {
        if (childNodes[i].enabled == '0') {
            childNodes[i].font = {'color': 'red'};
            if (childNodes[i].isParent.toString() == "true") {
                childNodes[i].iconSkin = 'pIcon02';
            } else {
                childNodes[i].iconSkin = 'icon02';
            }
        }
    }
    return childNodes;
}

function getFont(treeId, node) {
    return node.font ? node.font : {};
}

var zNodes = [
    {id: 0, pId: -1, entryValue: $("#entityName").val(), isParent: true}
];

$(document).ready(function () {
    var treeObj = $.fn.zTree.init($("#zTree"), setting, zNodes);
    // 获取根节点
    var root = treeObj.getNodeByTId("zTree_1");
    // 展开根节点
    treeObj.expandNode(root, true, false, true);

    $('#batchSaveTreeList').on('click', function () {
        var parentId = treeObj.getCheckedNodes()[0].id;
        $.ajax({
            type: 'post',
            url: 'listEntry/saveBatchValues',
            data: {
                listId: $("#entityId").val(),
                parentId: parentId,
                entryValues: $('#batchAddTreeList #treeListEntryValues').val(),
                listNameApi: $("#entityApiName").val()
            },
            success: function (data) {
                if (!data.success) {
                    //alert(data.reason);
                    $("#treeListTip").html(data.reason);
                } else {
                    $("#treeListTip").html("");
                    $('#batchAddTreeList').modal('hide');
                    reSyncNode(treeObj.getCheckedNodes()[0]);
                }
            }
        });
    });

    $('#saveTreeList').on('click', function () {
        var validate = $('#treeListForm').validate({
            rules: {
                entryValue: {required: true, maxlength: 60},
                description: {maxlength: 60},
                sortNumber: {digits: true}
            },
            messages: {
                entryValue: {required: "必填字段!", maxlength: "最多可以输入{0}个字符!"},
                description: {maxlength: "最多可以输入{0}个字符!"},
                sortNumber: {digits: '只能输入整数'}
            },
            highlight: function (element) {
//	 				$(element).parent('td').find('label').before('<br>');
            },
            success: function (element) {
            }
        });
        if (validate.form()) {
            var idVal = $('#addTreeList input[name=id]').val();
            if (null == idVal || "" == idVal || "" == $.trim(idVal)) {
                $('#addTreeList input[name=parentId]').val(treeObj.getCheckedNodes()[0].id);
            } else {
                //选中的节点
                var checkedNodes = treeObj.getCheckedNodes();
                if (checkedNodes.length > 0) {
                    var node = checkedNodes[0].getParentNode();
                    $('#addTreeList input[name=parentId]').val(node.id);
                }
            }

            var arr = $('#treeListForm').serializeArray();
            var param = {};
            for (var i = 0; i < arr.length; i++) {
                param[arr[i].name] = arr[i].value;
            }
            $.ajax({
                type: "post",  //提交方式
                dataType: "json", //数据类型
                data: param,
                async: false,
                url: "listEntry/saveOrUpdateNode", //请求url
                success: function (data) { //提交成功的回调函数
                    if (!data.success) {
                        //alert(data.reason);
                        $("#treeEntryTip").html(data.reason);
                    } else {
                        $("#treeEntryTip").html("");
                        $('#addTreeList').modal('hide');
                        reSyncNode(treeObj.getCheckedNodes()[0]);
                    }
                }
            });
        }
    });
});

function reSyncNode(node) {
    var treeObj = $.fn.zTree.getZTreeObj('zTree');
    if ($('#treeListForm input[name=update]').val()) {
        node.entryValue = $('#treeListForm input[name=entryValue]').val();
        node.description = $('#treeListForm input[name=description]').val();
        node.sortNumber = $('#treeListForm input[name=sortNumber]').val();
        node.apiName = $('#treeListForm input[name=apiName]').val();
        node.enabled = $('#treeListForm select[name=enabled]').val();
        if (node.enabled == '0') {
            node.font = {'color': 'red'};
            if (node.isParent) {
                node.iconSkin = 'pIcon02';
            } else {
                node.iconSkin = 'icon02';
            }
        } else {
            node.font = {'color': 'black'};
            if (node.isParent) {
                node.iconSkin = "pIcon01";
            } else {
                node.iconSkin = "icon01";
            }
        }
        treeObj.updateNode(node);
    } else if (node.isParent == false) {
        node.isParent = true;
        treeObj.updateNode(node);
    }
    treeObj.reAsyncChildNodes(node, "refresh");
}

function zTreeOnDblClick(event, treeId, treeNode) {
    if (treeNode.id == 0) {
        $("#threeAddTip").html("不能修改根节点!").show();
        return;
    } else {
        $("#threeAddTip").html("不能修改根节点!").hide();
    }
    var tree = $.fn.zTree.getZTreeObj('zTree');
    var node = tree.getNodeByTId(treeNode.tId);
    // 选中被双击的节点
    tree.checkNode(node, true, false);
    $('#zTree').data('radioCheckedNode', treeNode);
    $('#treeListForm input[name=update]').val('true');
    $('#treeListForm input[name=id]').val(treeNode.id);
    $('#treeListForm input[name=parentId]').val(treeNode.parentId);
    $('#treeListForm input[name=listId]').val(treeNode.listId);
    $('#treeListForm input[name=entryValue]').val(treeNode.entryValue);
    $('#treeListForm input[name=description]').val(treeNode.description);
    $('#treeListForm input[name=sortNumber]').val(treeNode.sortNumber);
    $('#treeListForm input[name=apiName]').val(treeNode.apiName);
    $('#treeListForm select[name=enabled]').val(treeNode.enabled);
    $('#addTreeList').modal('show');
}

function showAddTreeList() {
    var tree = $.fn.zTree.getZTreeObj('zTree');
    if (tree.getCheckedNodes().length == 0) {
        $("#threeAddTip").html("请选择父节点!").show();
        return;
    } else {
        $("#threeAddTip").html("请选择父节点!").hide();
    }
    $('#treeListForm input[name=update]').val('');
    $('#treeListForm input[name=id]').val('');
    $('#treeListForm input[name=parentId]').val('');
    $('#treeListForm input[name=entryValue]').val('');
    $('#treeListForm input[name=description]').val('');
    $('#treeListForm input[name=sortNumber]').val('');
    $('#treeListForm input[name=apiName]').val('');
    $('#treeListForm select[name=enabled]').val('1');
    $('#addTreeList').modal('show');
}

function showBatchAddTreeList() {
    var tree = $.fn.zTree.getZTreeObj('zTree');
    if (tree.getCheckedNodes().length == 0) {
        $("#threeAddTip").html("请选择父节点!").show();
        return;
    } else {
        $("#threeAddTip").html("请选择父节点!").hide();
    }
    $('#batchAddTreeList #entryValues').val('');
    $('#treeListForm input[name=update]').val('');
    $('#batchAddTreeList').modal('show');
}